import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputVal: 'aa',
    nowType: 'all'
  },
  mutations: {
    setListData(state, list) {
      state.list = list
    },
    setInputVal(state, val) {
      state.inputVal = val
    },
    addItem(state) {
      state.list.push({
        "id": state.list.length,
        "info": state.inputVal,
        "done": false
      })
      state.inputVal = ''
    },
    removeItem(state, id) {
      let i = state.list.findIndex(item=>{
        return item.id == id
      })

      if(i !== -1) {
        state.list.splice(i, 1)
      }
    },
    changeDone(state, params) {
      let i = state.list.findIndex(item => {
        return item.id === params.id
      })

      state.list[i].done = params.done
    },
    clearDone(state) {
      state.list = state.list.filter(item => !item.done)
    },
    changeType(state, type) {
      state.nowType = type
    }
  },
  actions: {
    getListData(context) {
      axios.get('/data.json').then(({data}) => {
        context.commit('setListData', data)
      })
    }
  },
  getters: {
    unDoneNum(state) {
      let arr = state.list.filter((item) => {
        return item.done === false
      })
      let num = arr.length
      return num
    },
    changeList(state) {
      if(state.nowType == 'all') {
        return state.list
      } else if(state.nowType == 'undone') {
        return state.list.filter(item => !item.done)
      } else if(state.nowType == 'done') {
        return state.list.filter(item => item.done)
      } else {
        return state.list
      }
    }
  }
})
